//
//  CZOAuthViewController.swift
//  weiBo
//
//  Created by apple on 16/5/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
//appKey
let weiboAppKet = "3030344696"
//授权回调页
let WeiboRedirect_Uri = "http://www.baidu.com"
//WeiboAppSecret
let WeiboAppSecret = "c5f6ce23613f0fad93c0600e45ec3110"


class CZOAuthViewController: UIViewController {
   
    //创建一个webview
    
    private lazy var webView : UIWebView = UIWebView()
    
    //自定义View
    override func loadView() {
        //设置代理
        webView.delegate = self
        
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavUI()
        
        //设置请求网址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(weiboAppKet)&redirect_uri=\(WeiboRedirect_Uri)"
        
        //设置请求数据
        let request = NSURLRequest(URL: NSURL(string: url)!)
        
        //加载登录界面
        webView.loadRequest(request)
    }
    
    private func setUpNavUI()
    {
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 15, target: self, action: "autoFillAction")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.title = "微博登录"
        
    
    }
    
    //右键的点击事件
    @objc private func autoFillAction(){
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18633232227'; document.getElementById('passwd').value = 'haoyangde123'")
    
    }
    //左键的点击事件
    @objc private func cancelAction(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}


//实现UIWebView的代理方法

extension CZOAuthViewController : UIWebViewDelegate
{
    //将要加载函数请求的函数
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        guard let url = request.URL else
        {
            return false
        }
        //取反不是以itcast打头的URL  不是我们关心的url
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
            return true
        }
        //取得itcast打头的url
        //query就是？后面的东西
        if let query = url.query where query.hasPrefix("code"){
            let code = query.substringFromIndex("code=".endIndex)
            CZUserCountViewModel.sharedUserAccount.requestAccessToken(code, complete: { (isSuccess) -> () in
                if isSuccess {
//                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                    
                }else{
                    SVProgressHUD.showErrorWithStatus("登录失败")
                    
                }
            })
        }else{
            dismissViewControllerAnimated(true, completion: nil)
        }
      
        return false
    }
    
    }

    
    //开始加载调用
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    
    










